package com.mrli.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.Map;

/**
 * description
 *
 * @author LiDaShuai
 * @version 1.0
 * @project mrli-mall-auto-issu
 * @date: 2023/2/8 16:49
 * @copyright 2009–2022xxxxx all rights reserved.
 */
@Component
@Slf4j
public class MessageHandShakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("握手拦截器执行");
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            String authorization = req.getHeader("Sec-WebSocket-Protocol");
            if (StringUtils.isEmpty(authorization)||"null".equals(authorization)){
                return false;
            }
            String path = request.getURI().getPath();
            if (!"/websocket/0".equals(path)){
                return false;
            }
            attributes.put("userId", new BigInteger(authorization));
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        if(request instanceof ServletServerHttpRequest){
            HttpServletRequest serverRequest = ((ServletServerHttpRequest) request).getServletRequest();
            HttpServletResponse httpResponse = ((ServletServerHttpResponse) response).getServletResponse();
            if (!StringUtils.isEmpty(serverRequest.getHeader("Sec-WebSocket-Protocol"))) {
                httpResponse.addHeader("Sec-WebSocket-Protocol", serverRequest.getHeader("Sec-WebSocket-Protocol"));
            }
            log.info("HandshakeInterceptor afterHandshake end...");
        }
    }
}

